import React, { createContext, useContext } from "react";
import { Todo } from "./interface";
import { ADD_TODO, CHANGE_TODO, DELETE_TODO } from "./action";

export const TasksContext = createContext<Todo[] | null>(null);
export const TasksDispatchContext = createContext<React.Dispatch<Action> | null>(null);

export const initialTodos: Todo[] = [
  { id: 0, title: "吃饭", done: true },
  { id: 1, title: "看画", done: false },
  { id: 2, title: "玩滚滚", done: false }
];

interface Action {
  type: string;
  payload?: {
    id?: number;
    title?: string;
    todo?: Todo;
  };
}

export function taskReducer(draft: Todo[], action: Action) {
  console.log(action);
  switch (action.type) {
    case ADD_TODO: {
      draft.unshift({
        id: action?.payload?.id ?? draft.length,
        title: action?.payload?.title ?? "",
        done: false
      });
      break;
    }
    case CHANGE_TODO: {
      const index = draft.findIndex(todo => todo.id === action?.payload?.todo?.id);
      draft[index] = action.payload?.todo ?? draft[index];
      break;
    }
    case DELETE_TODO: {
      return draft.filter(t => t.id !== action?.payload?.id);
    }
    default: {
      throw Error("未知 action: " + action.type);
    }
  }
}

export function useTasks() {
  return useContext(TasksContext);
}

export function useTasksDispatch() {
  return useContext(TasksDispatchContext);
}
